package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import com.tanhua.server.interceptors.UserHolder;
import com.tanhua.server.utils.RelativeDateFormat;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MovementService {

    @Reference
    private MovementApi movementApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private CommentApi commentApi;

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Reference
    private VisitorsApi visitorsApi;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public ResponseEntity saveMovement(Movement movement, MultipartFile[] imageContent) throws Exception {
//
//        需要给movement设置UserId和图片地址

        movement.setUserId(UserHolder.getUserId());
        List<String> medias = new ArrayList<>();
        for (MultipartFile ic : imageContent) {
            String picPath = ossTemplate.upload(ic.getOriginalFilename(), ic.getInputStream());
            medias.add(picPath);
        }
        movement.setMedias(medias);
        String movementId = movementApi.saveMovement(movement);

//         向MQ中放一个动态id
        rocketMQTemplate.convertAndSend("movement_check_topic",movementId);

         return ResponseEntity.ok(null);
    }

//    查询好友动态
    public ResponseEntity queryFriendMovements(Integer page, Integer pagesize) {

        PageResult pageResult =  movementApi.queryFriendMovements(UserHolder.getUserId(),page,pagesize);
        List<Movement> items = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
//            UserInfo+Movement---->MovementsVo
            MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement, userInfo);

            list.add(movementsVo);
        }
        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);
    }



//    查询推荐动态
    public ResponseEntity queryRecommendMovements(Integer page, Integer pagesize) {

        PageResult pageResult =  movementApi.queryRecommendMovements(UserHolder.getUserId(),page,pagesize);
        List<Movement> items = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
//            UserInfo+Movement---->MovementsVo
            MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement, userInfo);

            list.add(movementsVo);
        }
        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);

    }

//    查询自己的动态
    public ResponseEntity queryMyselfMovements(Integer page, Integer pagesize, Long userId) {
//        userId如果有值就查询这个用户的动态 如果没有值就是查当前登录人
        if(userId==null){
            userId = UserHolder.getUserId();
        }

        PageResult pageResult =  movementApi.queryMyselfMovements(userId,page,pagesize);
        List<Movement> items = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
        for (Movement movement : items) {

            if(movement.getState()!=1){ //动态未审核
                continue;
            }

            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
//            UserInfo+Movement---->MovementsVo
            MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement, userInfo);


            list.add(movementsVo);
        }
        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);

    }

    public MovementsVo movementAndUserInfoToMovementVo(Movement movement, UserInfo userInfo) {
        MovementsVo movementsVo = new MovementsVo();
        BeanUtils.copyProperties(userInfo, movementsVo); //拷贝后发现userId和tags无法赋值
        movementsVo.setUserId(userInfo.getId());
        if (StringUtils.isNotBlank(userInfo.getTags())) {
            movementsVo.setTags(userInfo.getTags().split(","));
        }
        BeanUtils.copyProperties(movement, movementsVo);//发现有4个需要手动赋值
        movementsVo.setId(movement.getId().toString()); //一定要注意这个不要少！！！！！！
        movementsVo.setImageContent(movement.getMedias().toArray(new String[]{}));
        movementsVo.setDistance("500米以内");
        movementsVo.setCreateDate(RelativeDateFormat.format(new Date(movement.getCreated())));

        //            判断当前登录人对这个圈子是否点赞   select *  from  Comment where userId=? and publishId=?? and commentType=1
        if (redisTemplate.hasKey("publish_like_" + movement.getId().toString() + "_" + UserHolder.getUserId())) {
            movementsVo.setHasLiked(1);
        } else {
            movementsVo.setHasLiked(0);
        }


        if (redisTemplate.hasKey("publish_love_" + movement.getId().toString() + "_" + UserHolder.getUserId())) {
            movementsVo.setHasLoved(1);
        } else {
            movementsVo.setHasLoved(0);
        }

        return movementsVo;
    }

//    动态点赞
    public ResponseEntity like(String movementId) {
//        1、向Comment添加一条数据   2、修改Movement的点赞数据 +1
        Comment comment = new Comment();
//        comment.setId(new ObjectId());  在dubbo那边赋值
        comment.setPublishId(new ObjectId(movementId)); //有可能是圈子ID、小视频id 、评论id
        comment.setCommentType(1);   //评论类型，1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
//        comment.setContent(); //评论的内容
        comment.setUserId(UserHolder.getUserId()); //
//        comment.setLikeCount(); //当前评论收到的点赞数据
//        comment.setCreated();  在dubbo那边赋值

//        comment.setPublishUserId(); //圈子的作者   在dubbo那边赋值

       Integer likeCount = commentApi.saveComment(comment);

//       在redis中做记录 谁对哪个圈子点赞
        redisTemplate.boundValueOps("publish_like_"+movementId+"_"+UserHolder.getUserId()).set("");

      return ResponseEntity.ok(likeCount);

    }

    //    动态取消点赞
    public ResponseEntity dislike(String movementId) {
//        1、向Comment删除一条数据  delete from comment where userId=?? and publishId=?? and commentType=??      2、修改Movement的点赞数据 -1
        Comment comment = new Comment();

        comment.setPublishId(new ObjectId(movementId)); //有可能是圈子ID、小视频id 、评论id
        comment.setCommentType(1);   //评论类型，1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞

        comment.setUserId(UserHolder.getUserId()); //


        Integer likeCount = commentApi.deleteComment(comment);
//        Integer likeCount = commentApi.deleteComment(movementId,1,UserHolder.getUserId());

//       在redis中删除记录 谁对哪个圈子点赞
        redisTemplate.delete("publish_like_"+movementId+"_"+UserHolder.getUserId());

        return ResponseEntity.ok(likeCount);
    }

    public ResponseEntity love(String movementId) {
        //        1、向Comment添加一条数据   2、修改Movement的喜欢数据 +1
        Comment comment = new Comment();
//        comment.setId(new ObjectId());  在dubbo那边赋值
        comment.setPublishId(new ObjectId(movementId)); //有可能是圈子ID、小视频id 、评论id
        comment.setCommentType(3);   //评论类型，1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
//        comment.setContent(); //评论的内容
        comment.setUserId(UserHolder.getUserId()); //
//        comment.setLikeCount(); //当前评论收到的点赞数据
//        comment.setCreated();  在dubbo那边赋值
//        comment.setPublishUserId(); //圈子的作者   在dubbo那边赋值

        Integer likeCount = commentApi.saveComment(comment);

//       在redis中做记录 谁对哪个圈子点赞
        redisTemplate.boundValueOps("publish_love_"+movementId+"_"+UserHolder.getUserId()).set("");

        return ResponseEntity.ok(likeCount);


    }

//    取消喜欢
    public ResponseEntity unlove(String movementId) {
        //        1、向Comment删除一条数据  delete from comment where userId=?? and publishId=?? and commentType=??      2、修改Movement的喜欢数据 -1
        Comment comment = new Comment();

        comment.setPublishId(new ObjectId(movementId)); //有可能是圈子ID、小视频id 、评论id
        comment.setCommentType(3);   //评论类型，1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞

        comment.setUserId(UserHolder.getUserId()); //


        Integer likeCount = commentApi.deleteComment(comment);
//        Integer likeCount = commentApi.deleteComment(movementId,1,UserHolder.getUserId());

//       在redis中删除记录 谁对哪个圈子点赞
        redisTemplate.delete("publish_love_"+movementId+"_"+UserHolder.getUserId());

        return ResponseEntity.ok(likeCount);
    }

    public ResponseEntity queryMovementById(String movementId) {
//        1、从mongo中查询 Movement
       Movement movement = movementApi.queryMovementById(movementId);
//        2、从mysql中查询user
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());

        MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement,userInfo);

        return ResponseEntity.ok(movementsVo);
    }


    @Reference
    private RecommendUserApi recommendUserApi;

    public ResponseEntity queryVisitors(Integer num) {

        String timeStr = redisTemplate.boundValueOps("visitors_time_" + UserHolder.getUserId()).get();
        List<Visitors> visitorsList = null;
        if(StringUtils.isNotBlank(timeStr)){
            long time = Long.parseLong(timeStr);
            visitorsList = visitorsApi.queryVisitors(UserHolder.getUserId(),num,time);
        }else{ //第一次登录进入到首页
           visitorsList = visitorsApi.queryVisitors(UserHolder.getUserId(),num);
        }





        List<RecommendUserVo> list = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            UserInfo userInfo = userInfoApi.findById(visitors.getVisitorUserId());
            BeanUtils.copyProperties(userInfo,recommendUserVo);
            if(StringUtils.isNotBlank(userInfo.getTags())){
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            Long score = recommendUserApi.queryScore(UserHolder.getUserId(), visitors.getVisitorUserId());
            recommendUserVo.setFateValue(score);
            list.add(recommendUserVo);
        }


        redisTemplate.boundValueOps("visitors_time_"+UserHolder.getUserId()).set(new Date().getTime()+"");

        return ResponseEntity.ok(list);


    }
}
